import {
	workerLogin
} from '@/api/app/index.js'

export const IphonePageStatus = {
	Login: '',
	Register: '',
}


export const useAppStore = {
	currTabIndex: undefined,
	currTaskIndex: undefined,
	token: undefined,
	appId: undefined,
	loginRes: undefined,
	bottomHeight: undefined,
	isWgy: undefined,
	houseNames: undefined,
	resetInfo: undefined,
	registerPhone: undefined,
	/**
	 * 当前手机验证页面 状态
	 * Login - 登录验证 （已注册登录）
	 * Register - 注册验证 （获取手机号）
	 */
	phonePageStatus: IphonePageStatus,
	openId: undefined,

	wxAuthUserLocation: undefined,
	wxAuthSubscribeMessage: undefined,

	homeSlide: undefined,
	homeParams: undefined,
	// 是否有红点
	isNotiRed: undefined,
}


export const state = {
	currTabIndex: 0,
	currTaskIndex: 2,
	token: '',
	role: null,
	appId: '',
	loginRes: null,
	loginInfoRes: null,
	showSfyz: true,
	bottomHeight: '74px',
	isWgy: false,
	houseNames: null,
	resetInfo: false,
	registerPhone: '',
	phonePageStatus: IphonePageStatus.Login,
	openId: '',
	wxAuthUserLocation: false,
	wxAuthSubscribeMessage: false,
	homeSlide: true,

	homeParams: null,
	isNotiRed: false,
	nickName: '',
}



export const setStateTabIndex = (inddex) => {
	state.currTabIndex = inddex
}
const setStateTaskIndex = (inddex) => {
	state.currTaskIndex = inddex
}

export const setStateRole = (role) => {
	state.role = role
	state.isWgy = role.type === 1
}
const setStateAppId = (appId) => {
	state.appId = appId
}


export function setStateToken(token, auth = {
	wxAuthUserLocation: false,
	wxAuthSubscribeMessage: false
}) {
	state.token = token
	uni.setStorageSync('token', token)

	state.wxAuthUserLocation = auth?.wxAuthUserLocation
	state.wxAuthSubscribeMessage = auth?.wxAuthSubscribeMessage
	uni.setStorageSync('wxAuthUserLocation', auth?.wxAuthUserLocation)
	uni.setStorageSync('wxAuthSubscribeMessage', auth?.wxAuthSubscribeMessage)

	if (!uni.getStorageSync('startTime'))
		uni.setStorageSync('startTime', String(new Date().getTime()))
}

export function setStateName(name) {
	state.nickName = name
	uni.setStorageSync('nickName', state.nickName)
}

export function clearToken() {
	state.token = ''
	state.loginRes = null

	uni.removeStorageSync('token')
	uni.removeStorageSync('wxAuthUserLocation')
	uni.removeStorageSync('wxAuthSubscribeMessage')
	uni.removeStorageSync('startTime')
	// uni.clearStorageSync()
}

export function setLoginRes(loginRes) {
	state.loginRes = loginRes
	uni.setStorageSync('loginRes', JSON.stringify(loginRes))
}

export function setLoginInfoRes(loginInfoRes) {
	state.loginInfoRes = loginInfoRes
}

// 登录判断
export function login(paramData) {
	return new Promise((resolve, reject) => {
		workerLogin(paramData).then((loginRes) => {
			setLoginRes(loginRes)
			if (loginRes.code === 200) {
				setStateToken(loginRes.data.token)
				setStateName(loginRes.data.nickName)
				uni.reLaunch({
					url: '/pages/home/index',
				})

			}
			resolve(loginRes)
		}).catch((err) => {
			reject(err)
		})
	})
}

// -2无token或过期   -1待注册   0已注册--可以点击
function onClickDis() {
	const tokenStatus = getTokenStatus()
	if (tokenStatus !== 2)
		return -2
	if (state.loginRes === null)
		return -2

	if (state.loginInfoRes?.status === -1) {
		// uni.showToast({ title: '请注册', icon: 'none' })
		return -1
	}

	return 0
}

export function onClickDisToast() {
	const tokenStatus = getTokenStatus()
	if (tokenStatus !== 0) {
		uni.showModal({
			// TODO: 体验问题
			// title: '仅供内部使用，请您先注册登录',
			title: '提示',
			content: '您好，登录后可以体验完整功能',
			showCancel: true,
			success: ({
				confirm,
				cancel
			}) => {
				if (confirm) {
					uni.navigateTo({
						url: '/pages-sub/login/login'
					})
				}
			},
		})
		return -2
	}

	if (state.loginRes === null)
		return -1

	if (state.loginInfoRes?.status === -1) {
		const duration = 1500
		uni.showToast({
			title: '请先完善信息',
			icon: 'none',
			mask: true,
			duration
		})
		setTimeout(() => {
			uni.navigateTo({
				url: '/pages-sub/user/register?pageType=0'
			})
		}, duration)
		return -2
	}
	return 0
}

// 获取用户状态
export function onClickDisStatus() {
	const tokenStatus = getTokenStatus()
	if (tokenStatus !== 0) {
		return -2
	}
	if (state.loginRes === null)
		return -1

	if (state.loginInfoRes?.status === -1) {
		return -2
	}
	return 0
}

export function onCleanShowSfyz() {
	state.showSfyz = false
}


// 刷新信息（如注册，修改个人信息后，小区信息重置等）
function setResetInfo(isResetInfo) {
	state.resetInfo = isResetInfo
}
// 注册
export function setRegisterPhone(phone) {
	state.registerPhone = phone
}


/**
 * 获取当前token状态
 * -2 - 代表 未注册 或者 清除了缓存
 * -1 - 已过期
 * 0 - 未过期 （正常使用）
 */
export function getTokenStatus() {
	const token = uni.getStorageSync('token')
	const startTime = uni.getStorageSync('startTime')
	const loginRes = uni.getStorageSync('loginRes')
	const wxAuthUserLocation = uni.getStorageSync('wxAuthUserLocation')
	const wxAuthSubscribeMessage = uni.getStorageSync('wxAuthSubscribeMessage')

	// 没有值 代表 未注册 或者 清除了缓存
	if (!token || !startTime || !loginRes) {
		clearToken()
		setPhonePageStatus(IphonePageStatus.Login)
		return -2
	} else {
		// 有值代表已注册
		const EXPIRESTIME = 1000 * 60 * 60 * 24 * 6.5
		const date = new Date().getTime()
		// 已过期
		if (date - Number(startTime) > EXPIRESTIME) {
			clearToken()
			setPhonePageStatus(IphonePageStatus.Login)
			return -1
		} else {
			// 未过期
			// wx auth 只做 本地获取存储
			setStateToken(token, {
				wxAuthUserLocation,
				wxAuthSubscribeMessage
			})
			setLoginRes(JSON.parse(loginRes))
			setPhonePageStatus(IphonePageStatus.Login)
			return 0
		}
	}
}

export function setPhonePageStatus(status) {
	state.phonePageStatus = status
}

function setOpenId(openId) {
	state.openId = openId
}

const setHomeSlide = (slide) => {
	state.homeSlide = slide
}
const setHomeParams = (params) => {
	state.homeParams = params
}